import axios from 'axios'
import routes from '@/router'
import store from '@/store'
import { Message } from 'element-ui'
import i18n from '../i18n'
import { showFullScreenLoading, tryHideFullScreenLoading } from './auth'
export const http = axios.create({
  baseURL: store.state.baseURL,
  timeout: 1000 * 36,
  loading: true,
})

// 请求拦截器,在请求发出之前进行一些操作
http.interceptors.request.use(
  function (config) {
    let lang = localStorage.getItem('i18nLocale') || 'zh'
    if (!config.headers["lang"]) {
      config.headers["lang"] = lang;
    }
    let token = store.state.token
    if (token) {
      config.headers['Authorization'] = token
    }
    // 是否显示loading效果
    if (config.loading) {
      showFullScreenLoading()
    }
    return config
  },
  function (error) {
    Message(i18n.t('请求失败,请重试'))
    return Promise.reject(error)
  }
)

//响应拦截器异常处理
http.interceptors.response.use(
  (response) => {
    tryHideFullScreenLoading()
    if (!response) {
      Message(i18n.t('连接错误'))
    }
    if (response && !response.data.isSucceed) {
      if (response.data.code === 401) {
        sessionStorage.clear()
        routes.replace({ path: '/login' })
      }
      if (response.data.message) {
        Message(`${response.data.message}`)
      }
    }
    if (
      response &&
      response.config &&
      response.config.url.includes('/vito-sys/project/info')
    ) {
      return response.data
    }
    return response.data
  },
  (err) => {
    tryHideFullScreenLoading()
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          Message(i18n.t('错误请求'))
          break
        case 404:
          Message(i18n.t('当前资源不存在'))
          break
        case 500:
          Message(i18n.t('网络异常，请稍后重试'))
          break
        case 401:
          sessionStorage.clear()
          routes.replace({ path: '/login' })
          Message(i18n.t('登录超时,请重新登录'))
          break
        case 455:
          sessionStorage.clear()
          routes.replace({ path: '/login' })
          Message(i18n.t('授权文件过期,请重新上传'))
          break
        case 403:
          Message(i18n.t('拒绝访问'))
          break
        case 408:
          Message(i18n.t('请求超时'))
          break
        case 502:
          Message(i18n.t('网络错误'))
          break
        case 503:
          Message(i18n.t('服务不可用'))
          break
        default:
          Message(i18n.t('连接错误'))
      }
    } else {
      Message.error(i18n.t('当前网络不可用 请稍后重试'))
    }
    return false
  }
)

http.all = axios.all

//定义插件的配置来扩展 Vue 本身
const httpPlugin = {}
httpPlugin.install = function (Vue, options) {
  Vue.prototype.$http = http
}

export default httpPlugin
